//
//  ZLQWroteTravelNotesVC.swift
//  GoTravel
//
//  Created by lanou3g on 16/3/4.
//  Copyright © 2016年 SHH. All rights reserved.
//

import UIKit

//typealias Block = (string:String) -> Void

class ZLQWroteTravelNotesVC: UIViewController,UITextViewDelegate,UMSocialUIDelegate {

//    var passBlock:Block?
    
    var tableview = UITableView() //tableview
    var  headerview:UIView?//header视图
    var footerview:UIView?//footer视图
    var contentV:UITextView?//textview视图
    var toolbar:UIToolbar?//键盘上的自定义按钮
    var lab = UILabel()//textview上的label
    var umengBtn:UIButton?//分享button
    var hintL:UILabel? //提示信息
    var datePicker:UIDatePicker?//时间选择器
//    var dateTF:UITextField? //时间TF
    var number = Int()
    var imageArray = Array<UIImage>()
    var zlqpict:ZLQPictureCollecitionViewController!
    var string:String = "时间"
    var string1:String = "地点"
    var picData = Array<UIImage>() // 传过来的照片
    var string2:String?
    var deleteBut = UIButton() //删除datePicker
    var arrayDataArray = Array<String>()
    var number1:Int = 0
    
    var picture:UIImage!
    
    
//     collectionview 需要的属性
    var count:Int = 0
    //屏幕的宽和高
    let width = UIScreen.mainScreen().bounds.width
    let height = UIScreen.mainScreen().bounds.height
    var flowLayout:UICollectionViewFlowLayout?
    var collectionview:UICollectionView?
    var image:UIImage?
    
    let myCell = "myCellID"
    override func viewDidLoad() {
        super.viewDidLoad()
        print(self.string2)
        self.view.backgroundColor = UIColor.groupTableViewBackgroundColor()
        self.navigationItem.title = "写游记"
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "HTHome_Menu"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("showSideView"))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("saveAction"))
        
        
        
        addViews()
        addGestureRecognizer()
        
        
//        datePicker创建
        self.datePicker = UIDatePicker(frame: CGRectMake(0,self.view.frame.size.height,self.view.frame.size.width,0))
        self.datePicker?.backgroundColor = UIColor.whiteColor()
                    datePicker?.datePickerMode = .DateAndTime
        self.datePicker?.sizeToFit()
        self.datePicker?.locale = NSLocale.systemLocale()
        self.datePicker?.locale = NSLocale.init(localeIdentifier: "ZH_CH")
        self.datePicker?.addTarget(self, action: Selector("datechage:"), forControlEvents: UIControlEvents.ValueChanged)
        self.number = Int(self.view.frame.size.height*0.15)
        let formatter:NSDateFormatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd-HH-mm-ss"
        self.string = formatter.stringFromDate(self.datePicker!.date)

        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.tableview.reloadData()
        }
        
        
    }
  
    func showSideView()->Void {
        
        self.sideMenuViewController.presentLeftMenuViewController()
    }
//    添加手势
    func addGestureRecognizer() -> Void{
    
        let swipe:UISwipeGestureRecognizer = UISwipeGestureRecognizer()
        swipe.addTarget(self, action: Selector("addAction"))
        swipe.direction = .Up
        self.footerview!.addGestureRecognizer(swipe)

    }
//    手势响应事件
    func addAction() ->Void{
        
        UMSocialSnsService.presentSnsIconSheetView(self, appKey: nil, shareText: contentV?.text, shareImage: nil, shareToSnsNames: nil, delegate: self)
        
    }
    
//    保存事件
    func saveAction() ->Void{
    
        self.tableview.reloadData()
        
        let alert = UIAlertController(title: "提示", message: "该日志将被保存", preferredStyle: UIAlertControllerStyle.Alert)
        let action = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
        let action2 = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default) { (UIAlertAction) -> Void in
            
            print("==============\(self.contentV?.text)")
            print("----------\(self.string)")
            print(self.string1)
            print(self.arrayDataArray.count)

            let thread:NSThread = NSThread.init(target: self, selector: Selector("addThread"), object: nil)
            thread.start()
//            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
//                
//            })
       
//            ZLQSaveToCaches.sharedImage?.updateUserInfo(self.arrayDataArray)
            
        }
        
        alert.addAction(action)
        alert.addAction(action2)
        self.presentViewController(alert, animated: true, completion: nil)
    }
    
    func addThread() {
    
        autoreleasepool{
            
            let user = SHHGetUser.sharedGetUser
            user?.getUserInfo()
            let query = AVQuery(className: "UserInfo")
            query.whereKey("user_id", equalTo: user!.user_id)
            let object = query.findObjects().first
            
            let a = NSMutableArray()
            //            a.append(self.string)
            //            a.append((self.contentV?.text)!)
            //            a.append(self.string1)
            
            
            //            a.addObjectsFromArray(self.picData)
            //            a.addObject(self.picData)
            //            a.addObject(self.string2!)
            
            a.addObject((self.contentV?.text)!)
            a.addObject(self.string)
            a.addObject(self.string1)
            a.addObject(self.arrayDataArray)
            //            var b:Array<Array<String>> = (object!["user_array"] as? Array<Array<String>>)!
            var c = object!["user_array"] as? NSMutableArray
            //            b.append(a)
            //            c.addObjectsFromArray(a as [AnyObject])
            if c == nil {
                c = NSMutableArray()
                c?.addObject(a)
            } else {
                c?.addObject(a)
            }
            print("*******************\(c?.count)")
            object?.setObject(c, forKey: "user_array")
            object?.saveInBackgroundWithBlock({ (succeeded:Bool, error:NSError!) -> Void in
                
                if succeeded {
                    
                    let alert = UIAlertController(title: "提示", message: "保存成成功", preferredStyle: UIAlertControllerStyle.Alert)
                    let ac1 = UIAlertAction(title: "确定", style: UIAlertActionStyle.Cancel, handler: nil)
                    alert.addAction(ac1)
                    self.presentViewController(alert, animated: true, completion: nil)
                    
                    print("成功")
                }else{
                    print("失败")
                }
                
            })

        
        }
    
    }
  
//添加控件
    func addViews() {
        tableview.frame = self.view.bounds
        tableview.bounces = false
        self.view.addSubview(tableview)
        self.tableview.delegate = self
        self.tableview.dataSource = self
        self.tableview.registerClass(ZLQWroteTravelNotesCell.classForCoder(), forCellReuseIdentifier: "cell")
    
       
//        header 视图的添加
        headerview = UIView()
        headerview!.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height*0.4)
        headerview!.backgroundColor = UIColor.groupTableViewBackgroundColor()
        self.view.addSubview(headerview!)
        
        
//        collectionview  视图
        flowLayout = UICollectionViewFlowLayout()
        flowLayout?.sectionInset = UIEdgeInsetsMake(5, self.view.frame.size.height*0.005, self.view.frame.size.width*0.005, 0)
        flowLayout?.itemSize = CGSize(width: self.view.frame.size.width*0.18, height: self.view.frame.size.height*0.15)
        flowLayout?.minimumLineSpacing = 10
        flowLayout?.scrollDirection = .Horizontal
        collectionview = UICollectionView(frame: CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height*0.18), collectionViewLayout: flowLayout!)
        collectionview?.backgroundColor = UIColor.whiteColor()
        collectionview?.bounces = false
        collectionview?.delegate = self
        collectionview?.dataSource = self
        
        collectionview?.registerClass(ZLQPictureCollecitionCell.classForCoder(), forCellWithReuseIdentifier: myCell)
        headerview?.addSubview(collectionview!)

        collectionview!.frame = CGRectMake(headerview!.frame.size.width*0.04, headerview!.frame.size.height*0.55, headerview!.frame.size.width*0.9, self.view.frame.size.height*0.16)

     

//        textview视图
        contentV = UITextView()
        contentV?.frame = CGRectMake(headerview!.frame.size.width*0.04,headerview!.frame.size.height*0.12, headerview!.frame.size.width*0.9, self.headerview!.frame.size.height*0.4)
        contentV?.delegate = self
        contentV?.backgroundColor = UIColor.whiteColor()
         contentV?.keyboardType = UIKeyboardType.Default
        contentV?.returnKeyType = .Default
        headerview?.addSubview(contentV!)
        tableview.tableHeaderView = headerview
     
        
        lab.frame = CGRectMake(headerview!.frame.size.width*0.04,headerview!.frame.size.height*0.03, headerview!.frame.size.width*0.9, self.headerview!.frame.size.height*0.06)
        lab.text = "分享新鲜事:"
//        lab.backgroundColor = UIColor.greenColor()
        headerview?.addSubview(lab)
  

        
//        键盘上的回收按钮
       toolbar = UIToolbar(frame: CGRectMake(0,0,350,40))
        toolbar?.backgroundColor = UIColor.whiteColor()
        toolbar?.barStyle = .Black

        let doneButton:UIBarButtonItem = UIBarButtonItem(title: "隐藏键盘", style: UIBarButtonItemStyle.Done, target: self, action: Selector("dismissKeyBoard"))
        let array = [doneButton]
        toolbar?.setItems(array, animated: true)
       contentV?.inputAccessoryView = toolbar
        
        
//        footer 视图的添加
        footerview = UIView()
        footerview?.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height*0.34)
//        footerview?.backgroundColor = UIColor.groupTableViewBackgroundColor()
        tableview.tableFooterView = footerview
        
        hintL = UILabel(frame: CGRectMake(0,self.footerview!.frame.size.height*0.07,(self.footerview?.frame.size.width)!,self.footerview!.frame.size.height*0.1))
        hintL?.text = "向上滑动分享更多!"
        hintL?.textAlignment = .Center
        hintL?.alpha = 0.5
        footerview?.addSubview(hintL!)
        
    
    }
    
//    回收键盘
    func dismissKeyBoard() {
    
        self.contentV?.resignFirstResponder()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */
    
}
    
extension ZLQWroteTravelNotesVC:UITableViewDataSource,UITableViewDelegate {
   

    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 2
    }


    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {

        return 5
    }
    
//    分区数
     func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2;
    }

    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
     func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return self.view.frame.size.height*0.05;
    }
    
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
//       self.tableview.reloadData()
        var cell = tableView.dequeueReusableCellWithIdentifier("cell") as? ZLQWroteTravelNotesCell
        if cell == nil {
        cell = ZLQWroteTravelNotesCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
        }
        
        cell?.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
            
            if indexPath.section == 0{
                
                cell?.titleL?.text = self.string1
                

            } else if indexPath.section == 1 {
                
                cell?.titleL?.text = self.string

            }

 
        return cell!
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        
        if indexPath.section == 1{
            
            deleteBut.removeFromSuperview()
        deleteBut = UIButton(type: UIButtonType.Custom)
        deleteBut.frame = CGRectMake(self.view.frame.size.width, self.view.frame.size.height*0.62, self.view.frame.size.width*0.3, self.view.frame.size.height*0.1)
        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(0.3)
        UIView.setAnimationDelegate(self)
        datePicker?.frame = CGRectMake(0, self.view.frame.size.height*0.7, self.view.frame.size.width, self.view.frame.size.height*0.3)
        self.view.addSubview(datePicker!)
        deleteBut.frame = CGRectMake(self.view.frame.size.width*0.7, self.view.frame.size.height*0.62, self.view.frame.size.width*0.3, self.view.frame.size.height*0.1)
        deleteBut.setTitle("Done", forState: UIControlState.Normal)
        deleteBut.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        self.view.addSubview(deleteBut)
            
        UIView.commitAnimations()
        deleteBut.addTarget(self, action: Selector("deleteAction"), forControlEvents: UIControlEvents.TouchUpInside)
            
            
            
        } else {
            let a:ZLQSearchController = ZLQSearchController()

            
            a.passBlock = {
                (str) -> Void in
                print(str)
                self.string1 = str
                
                tableView.reloadData()
            }
            self.navigationController?.pushViewController(a, animated: true)
        
        }
    
    }
    func deleteAction() {
    
        deleteBut.removeFromSuperview()
        datePicker?.removeFromSuperview()
        
    }
    
    func datechage(pick:UIDatePicker){
    
        let formatter:NSDateFormatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd-HH-mm-ss"
        self.string = formatter.stringFromDate(pick.date)
        self.tableview.reloadData()
        
    }
    
    
}


// collectionView 视图的添加
extension ZLQWroteTravelNotesVC:UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIImagePickerControllerDelegate,UINavigationControllerDelegate{


    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
        let takePhotoAction = UIAlertAction(title: "照相", style: UIAlertActionStyle.Default) { (action:UIAlertAction) -> Void in
            
            //判断是否可以打开相机，模拟器此功能无法使用
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
                //调用系统相机
                let picker = UIImagePickerController()
                picker.sourceType = UIImagePickerControllerSourceType.Camera
                picker.delegate = self
                picker.allowsEditing = true
                self.presentViewController(picker, animated: true, completion: nil)
            }else{
                let alert = UIAlertController(title: "Error", message: "你没有摄像头", preferredStyle: UIAlertControllerStyle.Alert)
                let cancelAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: nil)
                alert.addAction(cancelAction)
                self.presentViewController(alert, animated: true, completion: nil)
            }
        }
        
        let photoAction = UIAlertAction(title: "从相册中选择", style: UIAlertActionStyle.Default) { (action:UIAlertAction) -> Void in
            //相册是可以用模拟器打开的
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
                let picker = UIImagePickerController()
                picker.delegate = self
                picker.allowsEditing = true
                picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
                self.presentViewController(picker, animated: true, completion: nil)
            }else{
                let alert = UIAlertController(title: "Error", message: "你没有照片", preferredStyle: UIAlertControllerStyle.Alert)
                let cancelAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: nil)
                alert.addAction(cancelAction)
                self.presentViewController(alert, animated: true, completion: nil)
            }
        }
        
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
        alert.addAction(takePhotoAction)
        alert.addAction(photoAction)
        alert.addAction(cancelAction)
        self.presentViewController(alert, animated: true, completion: nil)
        
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
        
        
        let a:NSIndexPath = (collectionview?.indexPathsForSelectedItems()?.first)!
        let cell = collectionview?.cellForItemAtIndexPath(a) as? ZLQPictureCollecitionCell
        cell?.picture?.image = info[UIImagePickerControllerOriginalImage] as? UIImage
        picker.dismissViewControllerAnimated(true, completion: nil)
        count+=1
        self.image = info[UIImagePickerControllerOriginalImage] as? UIImage
        self.picture = info[UIImagePickerControllerOriginalImage] as! UIImage
        let data = UIImagePNGRepresentation(self.picture)
        let file = AVFile(name: "image.png", data: data)
        file.saveInBackgroundWithBlock { (flag, error) -> Void in
//            print(error)
            self.arrayDataArray.append(file.url!)
        }
        file.saveInBackground()
//        if file.save() {
//            print("成功")
//        }else{
//            print("失败")
//        }
       print("-=-=-=-=-=-=-=\(file.url)")
        
//        let stri:NSString = NSString(data: <#T##NSData#>, encoding: <#T##UInt#>)
        
        
//        print("________________\(data)")
//        let urlString = NSString(data: data!, encoding: NSASCIIStringEncoding)
//        let string = String(data: data!, encoding: NSUTF8StringEncoding)
//        let string1 = NSString.init(data: data!, encoding: NSUTF8StringEncoding)
//        let url = NSURL(string: String(urlString))
//        print("+_+_+_+_+_+_+_+_+_+\(self.image!)")
//        self.arrayDataArray.append(self.image!)
        //        let a:NSURL = info(NSURL) as? NSURL
//        let data = UIImageJPEGRepresentation(self.image!, 1)
//        let urlString = NSString(data: data!, encoding: 1)
//        print("我尼玛\(urlString)")
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.collectionview?.reloadData()
        }
        
        
    }


    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if count == 0 {
            return 1
        }else{
        return count+1
            
        }
        
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionview?.dequeueReusableCellWithReuseIdentifier(myCell, forIndexPath: indexPath) as? ZLQPictureCollecitionCell


        if indexPath.row == count{
            cell!.picture?.image = UIImage(named:"2016-03-07 20.48.44")
        }
        
        
        return cell!
    }
    

}


